package com.m3958.firstgwt.server.dao;

import java.util.UUID;

import com.google.inject.Inject;
import com.m3958.firstgwt.client.types.ServerErrorCode;
import com.m3958.firstgwt.client.types.UserField;
import com.m3958.firstgwt.server.model.Group;
import com.m3958.firstgwt.server.model.MenuLevel;
import com.m3958.firstgwt.server.model.User;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.MySHAService;
import com.m3958.firstgwt.server.types.AppConstants;
import com.m3958.firstgwt.server.types.SmartError;
import com.m3958.firstgwt.shared.type.CommonField;


public class UserChangeStrategy  extends BaseModelChangeStrategy implements ModelChangeStrategy<User> {
	
	@Inject
	private MySHAService sha;
	
	@Inject
	private AppUtilService autils;
	
	private int initDiskQuota = 50 * 1024 * 1024;
	
	@Override
	public boolean extraPersistTask(User user) {
		if(!checkPassword(user))return false;
		if(!user.getFcUser()){
			if(!(autils.validateUserParams(getErrors(), getReqPs())))return false;
		}
		
		UserDao udao = injector.getInstance(UserDao.class);
		if(udao.findByLoginName(getReqPs().getStringValue(UserField.LOGIN_NAME.getValue()))!=null){
			getErrors().addError(new SmartError("用户名已注册！", ServerErrorCode.FORMAT_ERROR));
		}
		if(udao.findByEmail(getReqPs().getStringValue(CommonField.EMAIL.getValue()))!=null){
			getErrors().addError(new SmartError("电子邮件已注册！", ServerErrorCode.FORMAT_ERROR));
		}
		if(udao.findByMobile(getReqPs().getStringValue(UserField.MOBILE.getValue()))!=null){
			getErrors().addError(new SmartError("手机号码已注册！", ServerErrorCode.FORMAT_ERROR));
		}
		if(!getErrors().isEmpty())return false;
		user.setDiskQuota(initDiskQuota);
		user.setUsedDisk(0L);
		setInitMenuLevel(user);
		return true;
	}
	

	private void bindNewUser(User user) {
		if(getSu().isLogined()){
			User loginedUser = emp.get().find(User.class, getSu().getUserId());
			if(loginedUser.getFcUser() && loginedUser.getBindTo() < 1){
				loginedUser.setBindTo(user.getId());
				UserDao udao = injector.getInstance(UserDao.class);
				udao.smartUpdateBaseModel(loginedUser);
				getSu().setContent(user);
			}
		}
	}


	private void setInitMenuLevel(User user) {
		MenuLevelDao mldao = injector.getInstance(MenuLevelDao.class);
		MenuLevel ml = mldao.findByName(AppConstants.DEFAULT_MENULEVEL);
		user.setMenuLevel(ml);
	}

	private boolean setInitGroup(User user) {
		if(getReqPs() != null){
			Group g = emp.get().find(Group.class, getReqPs().getRelationModelId());
			if( g == null)return true;
			g.getUsers().add(user);
			injector.getInstance(GroupDao.class).update(g);
			return true;
		}else{
			return false;
		}
	}


	@Override
	public boolean extraUpdateTask(User user,User newModel) {
		if(!(autils.validateUserParams(getErrors(), getReqPs())))return false;
		checkPassword(newModel);
		newModel.setFcId(null);
		if(user.getFcId() == null || user.getFcId().isEmpty()){
			user.setFcId(UUID.randomUUID().toString().replace("-", ""));
		}
		MenuLevel ml = emp.get().find(MenuLevel.class, getReqPs().getIdValue(UserField.MENULEVEL_ID.getValue()));
		if(ml != null){
			user.setMenuLevel(ml);
		}
		if(getSu().isSuperman()){
			;
		}else{
			newModel.setDiskQuota(user.getDiskQuota());
		}
		
		return true;
	}
	


	@Override
	public boolean extraRemoveTask(User user) {
		return true;
	}
	
	private boolean checkPassword(User model) {
		String p;
		if(getReqPs() != null && getReqPs().getStringValue(UserField.PASSWORD.getValue()) != null){
			p = getReqPs().getStringValue(UserField.PASSWORD.getValue());
		}else{
			p = model.getPassword();
		}
		if(model.getPassword().length() != 28){
			model.setPassword(sha.encrypt(p));
		}
		return true;
	}

	@Override
	public boolean afterPersist(User user) {
		setInitGroup(user);
		if(!getReqPs().getStringValue("_bindnew", "").isEmpty()){
			bindNewUser(user);
		}
		return true;
	}
}
